package com.ase.按序打印;

/**
 * @author gyhstart
 * @create 2021/2/19 - 18:33
 **/
public class Solution {
    public static void main(String[] args) {

        Foo foo = new Foo();
        Thread thread1 = new Thread(() -> {
            try {
                foo.first(() -> System.out.println("first"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread thread2 = new Thread(() -> {
            try {
                foo.second(() -> System.out.println("second"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread thread3 = new Thread(() -> {
            try {
                foo.third(() -> System.out.println("third"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }

    static class Foo {

        //定义一个flag位
        int count = 1;

        public Foo() {
        }

        //使用synchronized,wait()先将线程放入等待池中，再利用notifyAll()唤醒所有线程
        public synchronized void first(Runnable printFirst) throws InterruptedException {
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            count++;
            notifyAll();
        }

        public synchronized void second(Runnable printSecond) throws InterruptedException {
            while (count != 2) {
                wait();
            }
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            count++;
            notifyAll();
        }

        public synchronized void third(Runnable printThird) throws InterruptedException {
            while (count != 3) {
                wait();
            }
            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
        }
    }
}
